package com.ezjie.ielts.module_word;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.application.YsApplication;
import com.ezjie.ielts.core.base.BaseBean;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.db.WordDao;
import com.ezjie.ielts.db.WordInstanceDao;
import com.ezjie.ielts.db.WordMeaningDao;
import com.ezjie.ielts.db.WordQuestionDao;
import com.ezjie.ielts.model.Eword;
import com.ezjie.ielts.model.EwordInstance;
import com.ezjie.ielts.model.EwordMeaning;
import com.ezjie.ielts.model.EwordQuestion;
import com.ezjie.ielts.model.Question;
import com.ezjie.ielts.model.ReviewToWordData;
import com.ezjie.ielts.model.ReviewWordData;
import com.ezjie.ielts.model.StudyRecord;
import com.ezjie.ielts.model.WordBean;
import com.ezjie.ielts.model.WordGroupBean;
import com.ezjie.ielts.model.WordGroupResponse;
import com.ezjie.ielts.module_word.adapter.ReviewChooseAdapter;
import com.ezjie.ielts.task.WordTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.ListUtils;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.PlayAnimationUtils;
import com.ezjie.ielts.util.PreferencesUtil;
import com.ezjie.ielts.util.SpeechTTSUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.util.WordHomeDataUtil;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

public class ReviewSummaryFragment extends Fragment implements OnClickListener {

	private static final String TAG = ReviewSummaryFragment.class.getSimpleName();

	private Context mContext;
	private TextView word;
	private TextView soundmark;// 音标
	private RelativeLayout sentence_ll;// 音标布局
	// private TextView navi_title_text;
	// private StudyRoundProgressBar progress;
	// private ProgressBar pb_progress;
	private RelativeLayout review_summery_rl;

	private RelativeLayout judge_rl;// 对错题布局
	private ImageButton yes, no;// 正确 &错误

	private ListView choose;// 选择题
	private ReviewChooseAdapter mChooseAdapter;
	private List<Question> mQuestions;

	private GridView fill_in;// 填空题

	private int answerType = 0;// 0为选择，1为对错，2为填空
	private int total;// 学习的总进度
	private int currentProgress;// 当前进度

	private ProgressDialog mProgressDialog;
	private WordGroupBean mGroupBean;
	private List<WordBean> words;// 所有的单词
	private int currentPosition;// 当前位置
	private long startTimeMillis = 0;
	private List<StudyRecord> studyRecords;
	private boolean isPause = true;// 判断是暂停还是完成练习

	private ImageView play;// 播放单词
	private LinearLayout word_ll;
	private AnimationDrawable animation;

	private int isReview;
	private Handler handler = new Handler();
	private WordDao dao;
	private WordInstanceDao instanceDao;
	private WordMeaningDao meaningDao;
	private WordQuestionDao questionDao;

	private WordTask mWordTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = getActivity();
		words = new ArrayList<WordBean>();
		studyRecords = new ArrayList<StudyRecord>();
		SpeechTTSUtil.getInstance(getActivity()).init();
		animation = PlayAnimationUtils.PlayWordAnimation(getActivity());
		dao = new WordDao(mContext);
		instanceDao = new WordInstanceDao(mContext);
		meaningDao = new WordMeaningDao(mContext);
		questionDao = new WordQuestionDao(mContext);
		mWordTask = new WordTask(mContext);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.layout_review_summary, null);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		initView(view);
		// Bundle bundle = getActivity().getIntent().getExtras();
		YsApplication myApplication = (YsApplication) getActivity().getApplication();
		ReviewWordData data = myApplication.getReviewWordData();
		if (data != null) {
			int wgid = data.getWgid();// bundle.getInt("wgid",1);
			isReview = data.getIsReview();// bundle.getInt("isReview",0);
			getWordGroup(String.valueOf(wgid));
		}
		setView();
	}

	private void initParentProgress() {
		// 控制父view显示进度
		Activity parentActivity = getActivity();
		if (parentActivity instanceof ReviewStudyManagerActivity) {
			ReviewStudyManagerActivity activity = (ReviewStudyManagerActivity) parentActivity;
			activity.showProgress(total, currentProgress);
		}
	}

	private void changeView2() {
		// 控制父view显示详情
		Activity parentActivity = getActivity();
		if (parentActivity instanceof ReviewStudyManagerActivity) {
			ReviewStudyManagerActivity activity = (ReviewStudyManagerActivity) parentActivity;
			activity.showView(ReviewStudyManagerActivity.SHOW_WORD);
		}
	}

	private void changeView() {
		// 控制父view显示详情
		Activity parentActivity = getActivity();
		if (parentActivity instanceof ReviewStudyManagerActivity) {
			ReviewStudyManagerActivity activity = (ReviewStudyManagerActivity) parentActivity;
			activity.showView(ReviewStudyManagerActivity.SHOW_DETAIL);
		}
	}

	private void setView() {
		// navi_title_text.setText(R.string.review_word_title);
		// progress.setEnabled(false);//设置不可拖动
		// backBtn.setOnClickListener(this);
		word_ll.setOnClickListener(this);
		play.setOnClickListener(this);
		choose.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!AppUtil.isFastClick()) {
					boolean isRight = mQuestions.get(position).isIs_right();
					view.setSelected(true);
					if (isRight) {
						if (getActivity() != null && words != null && currentPosition < words.size()) {
							WordBean wordBean = words.get(currentPosition);
							wordBean.setIs_passed(true);
							currentProgress++;
							// 学习记录
							long endTimeMillis = System.currentTimeMillis();
							int sec = (int) ((endTimeMillis - startTimeMillis) / 1000) + 1;
							StudyRecord studyRecord = new StudyRecord();
							studyRecord.setWid(wordBean.getWid());
							studyRecord.setIs_passed(true);
							studyRecord.setSec(sec);
							studyRecords.add(studyRecord);

							YsApplication myApplication = (YsApplication) getActivity().getApplication();
							myApplication.setStudyRecords(studyRecords);
							myApplication.setWords(words);
							myApplication.setWordBean(wordBean);
						}
						rightAnimation();
					} else {
						// wrongAnimation();
						if (getActivity() != null && words != null && currentPosition < words.size()) {
							WordBean wordBean = words.get(currentPosition);
							wordBean.setIs_passed(false);
							// 移动到最后
							words.remove(currentPosition);
							words.add(wordBean);

							// 学习记录
							long endTimeMillis = System.currentTimeMillis();
							int sec = (int) ((endTimeMillis - startTimeMillis) / 1000) + 1;
							StudyRecord studyRecord = new StudyRecord();
							studyRecord.setWid(wordBean.getWid());
							studyRecord.setIs_passed(false);
							studyRecord.setSec(sec);
							studyRecords.add(studyRecord);
							String wordString = word.getText().toString();
							String soundmarkString = soundmark.getText().toString();
							ReviewToWordData data = new ReviewToWordData(wordString, soundmarkString, currentPosition,
									mGroupBean.getWgid(), mGroupBean.getStatus(), isReview, total, currentProgress);
							YsApplication myApplication = (YsApplication) getActivity().getApplication();
							myApplication.setStudyRecords(studyRecords);
							myApplication.setWords(words);
							myApplication.setWordBean(wordBean);
							myApplication.setReviewToWordData(data);
							changeView();
						}
					}
				}
			}
		});
	}

	/**
	 * 正确执行的动画
	 */
	public void rightAnimation() {
		if (currentPosition <= mGroupBean.getWords().size()) {
			if (currentProgress < total) {
				isPause = true;
				handler.postDelayed(runnable, 50);
			} else {
				isPause = false;
				WordHomeDataUtil.putReviewedNum(mContext);// 提交已复习 更新单词首页数据
				if (6 == Integer.parseInt(mGroupBean.getStatus()) - 1) {
					WordHomeDataUtil.putWordMasterNum(mContext, mGroupBean.getWords().size());
					WordHomeDataUtil.putWordStudyingNum(mContext, -(mGroupBean.getWords().size()));
				}
				YsApplication myApplication = (YsApplication) getActivity().getApplication();
				myApplication.setmGroupBean(mGroupBean);
				Intent intent = new Intent(getActivity(), ReviewFinishActivity.class);
				// intent.putExtra("mGroupBean", mGroupBean);
				startActivity(intent);
				getActivity().finish();
			}
		}
	}

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			/*
			 * Animation left = AnimationUtils.loadAnimation(mContext,
			 * R.anim.open_to_left); review_summery_rl.setAnimation(left);
			 * initWord();
			 */
			changeView2();
		}
	};

	private void initView(View view) {
		mQuestions = new ArrayList<Question>();
		play = (ImageView) view.findViewById(R.id.play);
		word = (TextView) view.findViewById(R.id.word);
		soundmark = (TextView) view.findViewById(R.id.soundmark);
		judge_rl = (RelativeLayout) view.findViewById(R.id.judge_rl);
		yes = (ImageButton) view.findViewById(R.id.yes);
		no = (ImageButton) view.findViewById(R.id.no);
		choose = (ListView) view.findViewById(R.id.choose);
		fill_in = (GridView) view.findViewById(R.id.fill_in);
		sentence_ll = (RelativeLayout) view.findViewById(R.id.sentence_ll);
		review_summery_rl = (RelativeLayout) view.findViewById(R.id.review_summery_rl);
		word_ll = (LinearLayout) view.findViewById(R.id.word_ll);

		if (0 == answerType) {
			choose.setVisibility(View.VISIBLE);
			judge_rl.setVisibility(View.GONE);
			fill_in.setVisibility(View.GONE);
		} else if (1 == answerType) {
			choose.setVisibility(View.GONE);
			judge_rl.setVisibility(View.VISIBLE);
			fill_in.setVisibility(View.GONE);
		} else if (2 == answerType) {
			choose.setVisibility(View.GONE);
			judge_rl.setVisibility(View.GONE);
			fill_in.setVisibility(View.VISIBLE);
		}

		initWord();
	}

	private void initWord() {
		if (getActivity() != null && words != null && words.size() > 0) {
			getUnPassed();// 取出没有通过的单词
			startTimeMillis = System.currentTimeMillis();
		}
		if (words != null && words.size() > 0) {
			WordBean wordBean = words.get(currentPosition);
			Eword eword = dao.findByWordId(wordBean.getWid());
			List<EwordMeaning> wordmMeanings = meaningDao.findByWordId(wordBean.getWid());
			List<EwordQuestion> wordQuestions = questionDao.findByWordId(wordBean.getWid());
			List<EwordInstance> wordInstances = instanceDao.findByWordId(wordBean.getWid());

			// 第一个版本，只有选择题，要先判断是否有选择题，如果没有选择题，就删除这个单词，显示下一个，
			List<EwordQuestion> filterChooseQuestion = ListUtils.filterChooseQuestion(wordQuestions);

			if (filterChooseQuestion.size() == 0) {
				words.remove(wordBean);
				initWord();
				return;
			}

			if (eword != null && filterChooseQuestion != null) {
				wordBean.setWord(eword.word);
				wordBean.setPhonetic(eword.en_phonetic);
				wordBean.setMeans(ListUtils.transferMeanList(wordmMeanings));
				wordBean.setInstances(ListUtils.transferInstanceList(wordInstances));
				wordBean.setQuestion_type(ListUtils.transferQuestionType(filterChooseQuestion));
				wordBean.setQuestions(ListUtils.transferQuestionList(filterChooseQuestion));
				mQuestions = wordBean.getQuestions();
				if (mQuestions != null && mQuestions.size() > 0 && wordBean != null) {
					word.setText(Html.fromHtml(wordBean.getWord()));
					if (!TextUtils.isEmpty(wordBean.getPhonetic()) && !"[]".equals(wordBean.getPhonetic())) {
						sentence_ll.setVisibility(View.VISIBLE);
						soundmark.setText(Html.fromHtml(wordBean.getPhonetic()));
					} else {
						sentence_ll.setVisibility(View.INVISIBLE);
					}
					mChooseAdapter.setList(mQuestions);
					mChooseAdapter.notifyDataSetChanged();
				}
				initParentProgress();
			}
		}
	}

	private void getUnPassed() {
		if (words != null && words.size() > 0) {
			for (int i = 0; i < words.size(); i++) {
				WordBean wordBean = words.get(i);
				if (!wordBean.isIs_passed()) {
					currentPosition = i;
					break;
				}
			}
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		if (!hidden) {
			// 当切换界面的时候 hidden为false 切换下个单词
			initWord();
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		SpeechTTSUtil.getInstance(getActivity()).close();
		SpeechTTSUtil.getInstance(getActivity()).pause();
		// 保存进度
		saveProgress(mGroupBean.getWgid(), mGroupBean.getStatus(), isPause);
		if (isPause) {
			PreferencesUtil.putString(mContext, "temp_status", "1");
			PreferencesUtil.putInt(mContext, "finish_num", currentProgress);
		} else {
			PreferencesUtil.putString(mContext, "temp_status", "2");
			PreferencesUtil.putInt(mContext, "finish_num", currentProgress);
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_REVIEW_SUMMARY);
		MobclickAgent.onPause(mContext);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_REVIEW_SUMMARY);
		MobclickAgent.onResume(mContext);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.navi_back_btn:
			onBackPressed();
			break;
		case R.id.play:
		case R.id.word_ll:
			play.setImageDrawable(animation);
			animation.start();
			String text = word.getText().toString();
			if (!TextUtils.isEmpty(text)) {
				SpeechTTSUtil.getInstance(getActivity()).speak(text, animation);
			}
			break;
		}
	}

	public void onBackPressed() {
		if (getActivity() != null) {

			View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_rob_warn_dialog, null);

			final Dialog dialog = new Dialog(getActivity(), R.style.customDialog);
			dialog.setCanceledOnTouchOutside(false);
			dialog.setContentView(view);
			dialog.show();

			TextView tv_content = (TextView) view.findViewById(R.id.tv_content);
			tv_content.setText(R.string.word_first_exit_msg);
			LinearLayout ll_layout1 = (LinearLayout) view.findViewById(R.id.ll_layout1);
			LinearLayout ll_layout2 = (LinearLayout) view.findViewById(R.id.ll_layout2);
			ll_layout1.setVisibility(View.VISIBLE);
			ll_layout2.setVisibility(View.GONE);

			Button btn_yes = (Button) view.findViewById(R.id.btn_yes);
			Button btn_no = (Button) view.findViewById(R.id.btn_no);
			btn_no.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
					}
				}
			});
			btn_yes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 友盟统计
					MobclickAgent.onEvent(getActivity(), "word_review_backBtn");
					if (getActivity() != null && dialog != null && dialog.isShowing()) {
						dialog.cancel();
						isPause = true;
					}
					if (mGroupBean != null) {
						// 保存进度
						saveProgress(mGroupBean.getWgid(), mGroupBean.getStatus(), isPause);
						if (isPause) {
							PreferencesUtil.putString(mContext, "temp_status", "1");
							PreferencesUtil.putInt(mContext, "finish_num", currentProgress);
						} else {
							PreferencesUtil.putString(mContext, "temp_status", "2");
							PreferencesUtil.putInt(mContext, "finish_num", currentProgress);
						}
					}
				}
			});

		}

	}

	// 获取单词组
	private void getWordGroup(String wgid) {
		if (!NetworkUtil.isNetworkAvailable(mContext)) {
			AppUtil.showToast(mContext, R.string.no_network);
			return;
		}
		mWordTask.getWordGroup(wgid, "simple", new HttpRequestAbstractCallBack(mContext,true) {
			@Override
			public void onStartCallBack() {
				super.onStartCallBack();
				AppUtil.showProgressDialog(mContext);
			}

			@Override
			public void onSuccessCallBack(String result) {
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				AppUtil.dismissProgressDialog();
				play.setVisibility(View.VISIBLE);
				try {
					WordGroupResponse mGroupResponse = JSON.parseObject(result, WordGroupResponse.class);
					if (mGroupResponse != null && 200 == mGroupResponse.getStatus_code()) {
						String mGroupBeanStr = mGroupResponse.getData();
						if (!TextUtils.isEmpty(mGroupBeanStr)) {
							mGroupBean = JSON.parseObject(mGroupBeanStr, WordGroupBean.class);
							showData(mGroupBean);
						}
					} else {
						AppUtil.showToast(mContext, R.string.load_net_data_failure);
					}
				} catch (Exception e) {
					LogUtils.d("json数据异常");
					LogUtils.exception(e);
				}
			}

			private void showData(WordGroupBean mGroupBean) {
				if (mGroupBean.getWords().size() > currentPosition) {
					words = mGroupBean.getWords();
					if (this != null && words != null && words.size() > 0) {
						getUnPassed();// 取出没有通过的单词
						startTimeMillis = System.currentTimeMillis();
					}
					if (words.get(currentPosition).isIs_passed()) {
						return;
					}

					mChooseAdapter = new ReviewChooseAdapter(mContext);

					WordBean wordBean = words.get(currentPosition);
					Eword eword = dao.findByWordId(wordBean.getWid());
					List<EwordMeaning> wordmMeanings = meaningDao.findByWordId(wordBean.getWid());
					List<EwordQuestion> wordQuestions = questionDao.findByWordId(wordBean.getWid());
					List<EwordInstance> wordInstances = instanceDao.findByWordId(wordBean.getWid());

					// 第一个版本，只有选择题，要先判断是否有选择题，如果没有选择题，就删除这个单词，显示下一个，
					List<EwordQuestion> filterChooseQuestion = ListUtils.filterChooseQuestion(wordQuestions);

					if (filterChooseQuestion.size() == 0) {
						words.remove(wordBean);

						choose.setAdapter(mChooseAdapter);
						total = words.size();
						currentProgress = Integer.parseInt(mGroupBean.getPassed());

						initWord();
						return;
					}

					if (eword != null && filterChooseQuestion != null) {
						wordBean.setWord(eword.word);
						wordBean.setPhonetic(eword.en_phonetic);
						wordBean.setMeans(ListUtils.transferMeanList(wordmMeanings));
						wordBean.setInstances(ListUtils.transferInstanceList(wordInstances));
						wordBean.setQuestion_type(ListUtils.transferQuestionType(filterChooseQuestion));
						wordBean.setQuestions(ListUtils.transferQuestionList(filterChooseQuestion));

						mQuestions = wordBean.getQuestions();
						if (mQuestions != null && wordBean != null && mQuestions.size() > 0) {
							word.setText(Html.fromHtml(wordBean.getWord()));
							if (!TextUtils.isEmpty(wordBean.getPhonetic()) && !"[]".equals(wordBean.getPhonetic())) {
								sentence_ll.setVisibility(View.VISIBLE);
								soundmark.setText(Html.fromHtml(wordBean.getPhonetic()));
							} else {
								sentence_ll.setVisibility(View.INVISIBLE);
							}
							mChooseAdapter.setList(mQuestions);
						}
						choose.setAdapter(mChooseAdapter);
						total = Integer.parseInt(mGroupBean.getTotal());
						currentProgress = Integer.parseInt(mGroupBean.getPassed());
						if (words != null && words.size() > 0) {
							initParentProgress();
						}
					}
				}
			}

			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				super.onFailureCallBack(error, msg);
				LogUtils.e(msg);
				AppUtil.dismissProgressDialog();
				AppUtil.showToast(mContext, R.string.load_net_data_failure);
			}
		});
	}

	/**
	 * 保存进度 更改单词状态
	 */
	private void saveProgress(String wgid, String status, boolean isPause) {

		if (getActivity() != null) {
			if (!NetworkUtil.isNetworkAvailable(getActivity())) {
				AppUtil.showToast(getActivity(), R.string.no_network);
				return;
			}
			mWordTask.saveProgress(wgid + "", isPause + "", status + "", JSON.toJSONString(studyRecords),
					new HttpRequestAbstractCallBack(mContext,true) {
						@Override
						public void onStartCallBack() {
							super.onStartCallBack();
							if (null != getActivity()) {
								AppUtil.showProgressDialog(getActivity());
							}
						}

						@Override
						public void onSuccessCallBack(String result) {
							super.onSuccessCallBack(result);
							LogUtils.d(result);
							AppUtil.dismissProgressDialog();
							try {
								BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
								if (baseBean != null && 200 == baseBean.getStatus_code()) {
									// 提交成功
									getActivity().finish();
								} else {
									AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
								}
							} catch (Exception e) {
								LogUtils.d("json数据异常");
								LogUtils.exception(e);
							}
						}

						@Override
						public void onFailureCallBack(HttpException error, String msg) {
							super.onFailureCallBack(error, msg);
							LogUtils.e(msg);
							AppUtil.dismissProgressDialog();
							AppUtil.showToast(getActivity(), R.string.load_net_data_failure);
						}
					});
		}
	}

}
